package com.atguigu.srb.core.controller.api;


import com.alibaba.fastjson.JSON;
import com.atguigu.common.result.R;
import com.atguigu.srb.base.utils.JwtUtils;
import com.atguigu.srb.core.hfb.RequestHelper;
import com.atguigu.srb.core.pojo.vo.UserBindVO;
import com.atguigu.srb.core.service.UserBindService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * <p>
 * 用户绑定表 前端控制器
 * </p>
 *
 * @author tjf
 * @since 2022-01-03
 */
@RestController
@Api(tags = "会员账号绑定")
@RequestMapping("/api/core/userBind")
@Slf4j
public class UserBindController {

    private final UserBindService userBindService;

    public UserBindController(UserBindService userBindService) {
        this.userBindService = userBindService;
    }

    @ApiOperation("账户绑定提交数据")
    @PostMapping("/auth/bind")
    public R bind(@RequestBody UserBindVO userBindVO, @RequestHeader(required = false) String token) {
        // 确保用户已经登录,getUserId内部已做校验
        Long userId = JwtUtils.getUserId(token);

        // 根据userId做用户绑定
        String formStr = userBindService.commitBindUser(userBindVO, userId);
        return R.ok().data("formStr", formStr);
    }

    @ApiOperation("用户绑定异步回调接口")
    @PostMapping("/notify")
    public String notify(HttpServletRequest httpServletRequest) {
        // 获取汇付宝回调时携带的参数
        // 账户绑定异步回调接收参数如下：
        // {"agentUserId":"7",
        // "resultCode":"0001",
        // "sign":"8466d8d2e1f161fb53693d30ee179036",
        // "bindCode":"c5bae0a98db443df8b557e7eee23fa2c",
        // "resultMsg":"成功",
        // "timestamp":"1641990396981"}
        Map<String, Object> map = RequestHelper.switchMap(httpServletRequest.getParameterMap());
        log.info("账户绑定异步回调接收参数如下：" + JSON.toJSONString(map));

        // 校验签名
        if (!RequestHelper.isSignEquals(map)) {
            log.error("用户账户绑定异步回调签名验证错误：" + JSON.toJSONString(map));
            return "fail";
        }
        log.info("验证签名成功，开始绑定");

        // 更新user_bind, user_info两张表
        userBindService.notify(map);

        return "success";
    }
}

